import { getCuesIndustry } from "../../../../../service/api/api-cues-industry";
import { saveCuesSubmit } from "../../../../../service/api/api-cues-submit";
import Toast from 'tdesign-miniprogram/toast/index';
import Message from 'tdesign-miniprogram/message/index';
import { attachmentPreview } from "../../../../../service/api/api-vues-attachment";
var upFiles = require('../../../../../utils/upFiles')
// pages/cues/topic/create/createSubmit/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    access: {} as any,// 当前用户权限
    mode: 0,//上报线索
    topicId: '',//该线索的id
    titleName: '',//标题
    industryVisible: false,//行业抽屉是否打开
    industryIds: [],//选择的行业id
    industryName: '',//选择的行业名称
    industryList: [],//行业列表
    labelsList: [],//标签列表
    labelName: '',//标签名称
    showLabelList: [],//标签是否显示
    remarks: '',//备注
    articleContent: '',//选题内容

    previewVisible: false,//预览抽屉是否打开
    topicName: '',//选题计划
    currentUser: {},//当前用户
    viewshowConfirm: false,//是否直接提交的提示框
    //文件上传
    originFiles: [],//现有的图片列表
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },//图片配置
    upFileArr: [],//上传文件列表
    upPicturesArr: [],//上传相机拍照列表
    combinedArr: [],//所有上传文件
    maxUploadLen: 10,//最大上传量
    id: [],//上传文件的id列表
    upFilesBtn: true,//上传文件按钮是否显示
    previewData: {},//预览文件
    previewDataUrlType: 'preview',
    imageList: [],//现有的图片列表
    viewPreviewImageVisible: false,//是否预览图片
  },
  async onClickPreviewImage(e) {
    const file = e.currentTarget.dataset.file
    const index = e.currentTarget.dataset.index
    if (e.currentTarget.dataset.type === "file" || e.currentTarget.dataset.type === "video") {
      const response = await attachmentPreview({
        id: this.data.id[index],
      });
      if (response.code === 0) {
        this.setData({
          previewData: {
            title: file.name,
            onlinePreview: true,
            content: response.data,
          }
        })
        wx.navigateTo({
          url: '/pages/web/index?url=' + encodeURIComponent(this.data.previewData.content) + '&title=' + this.data.previewData.title + '&type=' + this.data.previewDataUrlType
        })
      } else {
        wx.showToast({
          title: '暂时无法预览',
          icon: 'error'
        })
      }
    } else {
      const imageList = this.data.combinedArr.map((item: any) => {
        if (item.type === 'image') {
          return item.path
        }
      })
      this.setData({
        imageList,
        viewPreviewImageVisible: true
      })
    }
  },
  // 点击上传选择图片或者视频
  uploadFiles: function (e: any) {
    var _this = this;
    let itemList = [];
    if (this.data.access.cuesTopicSubmitAttachmentVideo) {
      itemList.push('视频');
    }
    if (this.data.access.cuesTopicTubmitAttachmentPicture) {
      itemList.push('图片');
      itemList.push('拍摄');
    }
    if (this.data.access.cuesTopicSubmitAttachmentOffice) {
      itemList.push('文件');
    }
    // if (this.data.access.cuesTopicSubmitAttachmentOther) {
    //   itemList.push('压缩文件');
    // }
    wx.showActionSheet({
      itemList: itemList,
      success: function (res) {
        const url = '/cues/attachment/save'
        const directory = 'cues/submit'//目录
        if (itemList[res.tapIndex] === '拍摄') {
          upFiles.upFiles(_this, "pictrue", url, directory)
        } else if (itemList[res.tapIndex] === '视频') {
          //['mp4', 'avi', 'mov', 'wmv']
          upFiles.upFiles(_this, "video", url, directory)
        } else if (itemList[res.tapIndex] === '图片') {
          // ['jpg', 'jpeg', 'png', 'gif']
          upFiles.upFiles(_this, 'image', url, directory)
        } else {
          //['doc', 'docx', 'pdf', 'rar', 'zip']
          upFiles.upFiles(_this, 'file', url, directory)
        }
      },
      fail: function (res) {
      }
    })
  },
  //关闭图片预览
  onClosePreviewImage(e) {
    this.setData({
      viewPreviewImageVisible: false,
    });
  },
  // 删除上传图片 或者视频
  onDeleteFile: function (e: { currentTarget: { dataset: { index: any; }; }; }) {
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '您确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          let delNum = e.currentTarget.dataset.index;
          let upFileArr = _this.data.upFileArr;
          let id = _this.data.id
          upFileArr.splice(delNum, 1)
          id.splice(delNum, 1)
          _this.setData({
            upFileArr: upFileArr,
            id: id,
          })
          let upFilesArr = upFiles.getPathArr(_this);
          if (upFilesArr.length < _this.data.maxUploadLen) {
            _this.setData({
              upFilesBtn: true,
            })
          }
        } else if (res.cancel) {
        }
        let combinedArr = _this.data.upFileArr;
        _this.setData({
          combinedArr: combinedArr
        });
      }
    })
  },

  //点击已选文件
  handleClick(e) {
  },
  //输入标题
  onTitleNameInput(e) {
    this.setData({
      titleName: e.detail.value
    })
  },
  //打开选择行业的抽屉
  onIndustrySelectOpen() {
    this.setData({
      industryVisible: true,
      industryList: this.data.industryList,
    });
  },

  //点击选择行业
  industryItemClick(e) {
    //找到value对应的label
    const selectedLabels = e.detail.value.map(id => {
      const industry = this.data.industryList.find(item => item.value === id);
      return industry ? industry.label : '';
    });
    this.setData({
      industryIds: e.detail.value,
      industryName: selectedLabels
    })
  },

  //加载行业列表
  async loadCuesIndustryData() {
    try {
      const response = await getCuesIndustry();
      this.setData({
        industryList: response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      })
    } catch (error) { }
  },
  //输入标签
  onLabelNameInput(e) {
    const re = new RegExp('^[\u4E00-\u9FA5A-Za-z0-9]+$');
    for (const elem of e.detail.value) {
      if (re.test(elem)) {
      } else {
        wx.showToast({
          title: '只能输入汉字、英文字母和数字',
        })
        return;
      }
    }
    this.setData({
      labelName: e.detail.value
    })
  },
  handleAddLabels() {
    const { labelName, labelsList } = this.data;
    if (labelName && labelsList.indexOf(labelName) === -1) {
      this.data.labelsList.push(labelName);
      this.data.showLabelList.push(true);
      this.setData({
        labelName: '',
        labelsList: this.data.labelsList,
        showLabelList: this.data.showLabelList
      });
    } else {
      wx.showToast({
        title: '标签已存在',
        icon: 'none'
      });
    }
  },
  //删除标签
  handleTagClose(e) {
    const index = e.currentTarget.dataset.index
    this.data.labelsList.splice(index, 1); // 删除索引为index的标签
    this.data.showLabelList.splice(index, 1); // 删除对应的show数组元素
    this.setData({
      labelsList: this.data.labelsList,
      showLabelList: this.data.showLabelList
    })
  },
  //输入备注
  onRemarksInput(e) {
    this.setData({
      remarks: e.detail.value
    })
  },
  //输入选题内容
  onRrticleContentInput(e) {
    this.setData({
      articleContent: e.detail.value
    })
  },
  //取消提交
  handleCancel() {
    // wx.reLaunch({
    //   url: '/pages/cues/topic/details/topicRenderDetail/index'
    // })
    wx.navigateBack({
      delta: 1
    })
  },
  //预览
  async handlePreview() {
    if (this.data.titleName === '') {
      wx.showToast({
        title: "请输入标题",
        icon: 'none'
      })
      return false
    }
    if (this.data.industryIds.length === 0) {
      wx.showToast({
        title: "请选择行业",
        icon: 'none'
      })
      return false
    }
    if (this.data.labelsList.length === 0) {
      wx.showToast({
        title: "请输入标签",
        icon: 'none'
      })
      return false
    }
    if (this.data.articleContent === '') {
      wx.showToast({
        title: "请输入选题内容",
        icon: 'none'
      })
      return false
    }
    this.setData({
      previewVisible: true
    })
  },
  //点击确认后的弹窗关闭
  closeConfirmDialog() {
    this.setData({
      viewshowConfirm: false
    })

  },
  //点击确认后的弹窗打开
  openConfirmDialog() {
    if (this.data.titleName === '') {
      wx.showToast({
        title: "请输入标题",
        icon: 'none'
      })
      return false
    }
    if (this.data.industryIds.length === 0) {
      wx.showToast({
        title: "请选择行业",
        icon: 'none'
      })
      return false
    }
    if (this.data.labelsList.length === 0) {
      wx.showToast({
        title: "请输入标签",
        icon: 'none'
      })
      return false
    }
    if (this.data.articleContent === '') {
      wx.showToast({
        title: "请输入选题内容",
        icon: 'none'
      })
      return false
    }
    this.setData({
      viewshowConfirm: true
    })
  },
  //提交上报线索
  async handleSubmit() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '提交中',
      direction: 'column',
      duration: 3000,
      preventScrollThrough: true,
    });
    getApp().preventActive(async () => {
      const response = await saveCuesSubmit({
        topicId: this.data.topicId,
        articleContent: this.data.articleContent,
        articleIndustryIds: this.data.industryIds,
        articleLabels: this.data.labelsList,
        articleName: this.data.titleName,
        remarks: this.data.remarks,
        articleAttachments: this.data.id,
      });
      if (response.code === 0) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 5000,
          content: '提交成功',
        });
        wx.navigateBack({
          delta: 1
        })// 回到上一个界面
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: { topicId: any; mode: any; topicName: string, index: number }) {
   
    const { globalData: { currentUser, access } } = getApp();
    this.setData({
      access,
      topicId: options.topicId,
      mode: options.mode,
      topicName: options.topicName,
      currentUser
    })
    this.loadCuesIndustryData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.setStorageSync('submit-page', 'create');// 存到缓存
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})